﻿using NHibData.Repository;
using System.Web.Mvc;
using System.Data;

namespace NHibData.Attributes
{
    /// <summary>
    /// Attribute for specify, that ALL DB operation in controller action should be done in transaction    
    /// </summary>
    public class TransactionAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// Before action executing we begin transaction
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            NHibernateHelper.GetCurrentSession().BeginTransaction(IsolationLevel.ReadCommitted);
        }

        /// <summary>
        /// After action executed commit transaction
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {            
            //filterContext.Controller.ViewData.ModelState.
            

            if (filterContext.Exception == null && NHibernateHelper.GetCurrentSession().Transaction.IsActive && filterContext.Controller.ViewData.ModelState.IsValid == true)
            {
                NHibernateHelper.GetCurrentSession().Transaction.Commit();
            }
        }
    }
    //public class RequiresRoleAttribute : Controller
}
